﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XDCCManager.Attributes
{
	[AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)]
	class ActionOrderAttribute : Attribute
	{
		public ActionOrderAttribute(Type next)
		{
			if ((next != null) && !next.GetInterfaces().Contains(typeof(Model.Actions.IAction)))
				throw new ArgumentException("next", "Type must represent a XDCCManager.Model.Actions.IAction.");
			Next = next;
		}

		public Type Next { get; private set; }

		public static int ComputeInsertIndex(Model.Actions.ActionGroup group, Model.Actions.IAction action)
		{
			ActionOrderAttribute attr = action.GetType().GetCustomAttributes(typeof(ActionOrderAttribute), false)[0] as ActionOrderAttribute;
			return attr.ComputeInsertIndex(group, action.GetType(), null);
		}

		private int ComputeInsertIndex(Model.Actions.ActionGroup group, Type currentType, Type actionType)
		{
			int insertIndex;
			if (Next == null)
				insertIndex = group.Actions.Count;
			else
			{
				ActionOrderAttribute attr = Next.GetCustomAttributes(typeof(ActionOrderAttribute), false)[0] as ActionOrderAttribute;
				insertIndex = attr.ComputeInsertIndex(group, Next, currentType);
			}
			if (actionType != null)
				while ((insertIndex > 0) && (actionType.IsInstanceOfType(group.Actions[insertIndex - 1])))
					insertIndex--;
			return insertIndex;
		}
	}
}
